const express = require('express');

const multer = require('multer');
const fs = require("fs");
const pathLib = require("path");
const { UPLOAD_PATH, UPLOAD_IMG_SIZE, UPLOAD_IMG_TYPES } = require('../utils/constant');

const Result = require('../models/result');
const {
    getAll,
    getPage,
    getSearch,
    getByID,
    getCount,
    insert,
    batchInsert,
    update,
    del,
    batchDel,
    unDel,
    batchUnDel,
    absDel,
    batchAbsDel
} = require('../services/book');

const router = express.Router();

// 图片上传
// 会自动创建目录
router.post('/upload', multer({ dest: `${UPLOAD_PATH}/book` }).single('file'), (req, res, next) => {
    if (!req.file || req.file.length === 0) {
        return new Result('上传失败').fail(res);
    }
    var { originalname, destination, filename, mimetype, size, path } = req.file;
    var extname = pathLib.extname(originalname);
    var newname = pathLib.join(destination, filename + extname);
    var tmpTypes = mimetype.split('/')[1];
    if (UPLOAD_IMG_TYPES.indexOf(tmpTypes) < 0) {
        fs.unlinkSync(path);
        return new Result("请选择正确的图片格式").fail(res);
    }
    if (size > UPLOAD_IMG_SIZE) {
        fs.unlinkSync(path);
        return new Result(`图片体积超过${UPLOAD_IMG_SIZE / 1000}kb`).fail(res);
    }
    fs.rename(path, newname, function(err) {
        if (err) {
            fs.unlinkSync(path);
            new Result('重命名错误').fail(res);
        } else {
            var fileInfo = JSON.parse(JSON.stringify(req.file));
            fileInfo.path = newname;
            new Result(fileInfo, '上传成功').success(res);
        }
    })
});

// 获取所有
router.get('/getAll', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        getAll().then(list => {
            if (list) {
                new Result(list, "获取图书列表成功").success(res);
            }
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 分页查询
router.post('/getPage', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let pageIndex = req.query.pageIndex || 1;
        let pageSize = req.query.pageSize || 15;
        let orderBy = req.body.orderBy || {};
        let filters = req.body.filters || {};
        getCount().then(cnt => {
            getPage(pageIndex, pageSize, orderBy, filters).then(list => {
                if (list) {
                    new Result(list, "获取图书列表成功", {
                        total: cnt[0]['count(*)']
                    }).success(res);
                }
            }).catch(err => {
                new Result(err.sqlMessage).fail(res);
            });
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 搜索查询
router.post('/getSearch', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let orderBy = req.body.orderBy || {};
        let filters = req.body.filters || {};
        let top = req.body.top;
        getSearch(filters, orderBy, top).then(list => {
            if (list) {
                new Result(list, "搜索图书列表成功").success(res);
            }
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 根据ID查询
router.get('/getByID', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let id = req.query.id;
        getByID(id).then(list => {
            if (list) {
                new Result(list[0] || {}, "根据ID查询图书成功").success(res);
            }
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 获取总数
router.get('/getCount', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let id = req.query.id;
        getCount().then(cnt => {
            new Result(cnt[0]['count(*)'], "获取图书总数成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 单个插入
router.post('/insert', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let data = req.body;
        data.createUserID = decoded.userid;
        data.createDate = parseInt(Date.now() / 1000);
        insert(data).then(stats => {
            // stats.affectedRows
            new Result("图书添加成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 批量插入
router.post('/batchInsert', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let data = req.body;
        data.forEach(item => {
            item.createUserID = decoded.userid;
            item.createDate = parseInt(Date.now() / 1000);
        });
        batchInsert(data).then(stats => {
            // stats.affectedRows
            new Result("图书添加成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 修改数据
router.post('/update', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let data = req.body;
        let id = req.query.id;
        data.updateUserID = decoded.userid;
        data.updateDate = parseInt(Date.now() / 1000);
        update(data, id).then(stats => {
            // stats.affectedRows
            new Result("图书修改成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 逻辑删除
router.post('/del', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let id = req.body.id;
        let data = {
            delUserID: decoded.userid,
            delDate: parseInt(Date.now() / 1000)
        };
        del(data, id).then(stats => {
            // stats.affectedRows
            new Result("图书删除成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 批量逻辑删除
router.post('/batchDel', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let ids = req.body.ids;
        let data = {
            delUserID: decoded.userid,
            delDate: parseInt(Date.now() / 1000)
        };
        batchDel(data, ids).then(stats => {
            // stats.affectedRows
            new Result("图书删除成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 恢复删除的记录
router.post('/unDel', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let id = req.body.id;
        let data = {
            unDelUserID: decoded.userid,
            unDelDate: parseInt(Date.now() / 1000)
        };
        unDel(data, id).then(stats => {
            // stats.affectedRows
            new Result("图书恢复成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 批量恢复删除的记录
router.post('/batchUnDel', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let ids = req.body.ids;
        let data = {
            unDelUserID: decoded.userid,
            unDelDate: parseInt(Date.now() / 1000)
        };
        batchUnDel(data, ids).then(stats => {
            // stats.affectedRows
            new Result("图书恢复成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 物理删除
router.post('/absDel', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let id = req.body.id;
        absDel(id).then(stats => {
            // stats.affectedRows
            new Result("图书删除成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

// 批量物理删除
router.post('/batchAbsDel', (req, res, next) => {
    let decoded = req.user;
    if (decoded && decoded.username) {
        let ids = req.body.ids;
        batchAbsDel(ids).then(stats => {
            // stats.affectedRows
            new Result("图书删除成功").success(res);
        }).catch(err => {
            new Result(err.sqlMessage).fail(res);
        });
    } else {
        new Result('图书接口token解析失败').fail(res);
    }
});

module.exports = router;